var brandList, pbcList;

$(function () {

	   $("#search_reset").click(function(){
	  		 $("input").val("");
	         $("select").val("");
			 
	    });
	   var  storeDate = function(){
			var myDate = new Date();
			var year = myDate.getFullYear();
			var month = myDate.getMonth()+1;
			var day = myDate.getDate();
			var hours = myDate.getHours();
			var minutes = myDate.getMinutes();
			var seconds =myDate.getSeconds();
			if(month < 10 ){
				month = "0"+month;
			}
			if(day <10){
				day ="0"+day;
			}
			if(hours<10){
				hours = "0"+hours;
			}
			if(minutes<10){
				minutes ="0"+minutes;
			}
			if(seconds<10){
				seconds = "0"+seconds;
			}
			//var date = year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
			var date = year+"年"+month+"月"+day+"日";
			return date;
		}
	 //操作时间
		$('#produce_date').daterangepicker({
			"singleDatePicker": true,
			"timePicker": false,
			"timePicker24Hour": false,
			"timePickerSeconds": false,
			"parentEl": "200",
			locale: {
			  format:'YYYY-MM-DD',
		      applyLabel: '确认',
		      cancelLabel: '取消',
		      weekLabel: 'W',
		      customRangeLabel: 'Custom Range',
		      daysOfWeek:["日","一","二","三","四","五","六"],
		      monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
			}
		}, function(start, end, label) {
			$('#produce_date').val(start.format('YYYY-MM-DD'));
		});
		$('#produce_date').val('');
    //生成二维码
    $("[name='btn_new_save']").click(function () {
        var form = window.form_new;
        var pname = form.pname.value;
        var batch_nub = form.batch_nub.value;
        var qcname = form.qcname.value;
        var type = form.type.value;
        var produce_date = form.produce_date.value;
        var pms = form.pms.value;
        var pme = form.pme.value;
        var xms = form.xms.value;
        var xme = form.xme.value;
        var pid = form.pid.value;
        var leftnub = $("#_leftnub").val();
        if (!pname) {
            bootbox.balert("二维码批次输入有误！");
            return;
        }else{
        	var index = pname.lastIndexOf("_"); 
        	if(-1==index){
        		 bootbox.balert("产品名称选择有误！");
                 return;
        	}
        }
        // if(!produce_date){
        // 	bootbox.balert("生产日期输入有误！");
        //     return;
        // }
        produce_date = new Date(produce_date).getTime();
        if (!qcname) {
            bootbox.balert("二维码名称选择有误！");
            return;
        }else{
        	var index = qcname.lastIndexOf("_"); 
        	if(-1==index){
        		 bootbox.balert("二维码批次选择有误！");
                 return;
        	}
        }
        if(leftnub<=0){
      	  bootbox.balert("剩余数量不够！");
            return;
        }
        if (type==3  && isNaN(xme)) {
            bootbox.balert("箱码结束编码输入有误！");
            return;
        }
        if (isNaN(pme)) {
            bootbox.balert("瓶码结束编码输入有误！");
            return;
        }
        if(type==3  && parseInt(form.xmbdnum.value * form.pbccount.value) != form.bdnum.value){
        	bootbox.balert("箱码绑定数量和瓶码/盒码绑定数量不一致，请稍后再试！");
            return;
        }
        var msg =storeDate()+"，"+pname.split("_")[0]+"产品将绑定二维码"+form.bdnum.value+"枚，请确定是否绑定！";
        if(type==3){
        	msg =storeDate()+"，"+pname.split("_")[0]+"产品将绑定二维码箱码"+form.xmbdnum.value+"枚，瓶码"+form.bdnum.value+"枚，请确定是否绑定！";
        }
        
        bootbox.bconfirm(msg, function (re) {
            if (re) {
            	jQuery.ajax({
                    type:'post',
                    url:'/qrcodeproduct/add',
                    data:{'pname':pname,'batch_nub':batch_nub,'qcname':qcname,'type':type,'pms':pms,'pme':pme,'xms':xms,'xme':xme,'pid':pid,'produce_date':produce_date},
                    dataType:'json',
                    cache:false,
                    success:function(data){
                    	tipper.success("操作成功！");
                    	window.location.href=window.location.href; 
                    	window.location.reload; 
                    },
                    error:function (data, status) {
                        // tipper.danger(data.responseJSON.msg);
                        bootbox.alert({
                            message: data.responseJSON.msg,
                            size: "small",
                            title: "<i class='fa fa-info-circle text-yellow'></i> 提示"
                        });
                    }
               });
            }
        });
    });
    
    

    
    
    $("#type").on("change",function(){
    	$('#search_qcname').val('');
    	$('#_leftnub').val('');
		$('#xms').val('');
		$('#pms').val('');
		$('#xme').val('');
		$('#pme').val('');
    	var type_v = $("#type").val();
    	if("3"==type_v){
    		$('#xmsdiv').show();
    		$('#xmediv').show();
    		$('#xmbdnumdiv').show();
    		$('#pme').attr("readonly",true);
    		$('#_pbcid').val("");
    	}else{
    		$('#xmsdiv').hide();
    		$('#xmediv').hide();
    		$('#xmbdnumdiv').hide();
    		$('#_pbcid').val("");
    		$('#pme').attr("readonly",false)
    	}
    });
    
    $("#search_qcname").on("change",function(){
    	var sqcname = $("#search_qcname").val();
    	var index = sqcname.lastIndexOf("_"); 
    	if(-1==index){
    		return;
    	}
    	var qcid = sqcname.substring(index+1);
    	
    	var type = $("#type").val();
//    	console.log(type);
    	jQuery.ajax({
            type:'get',
            url:'/qrcode/count',
            data:{'id':qcid,"type":type},
            dataType:'json',
            cache:false,
            success:function(data){
            	if(1==type || 2==type){
            		$('#_leftnub').val(data.data.count);
            		$('#pms').val(data.data.minid);
            		$('#pme').val(data.data.maxid);
            		$('#pme_bak').val(data.data.maxid);
            		$('#pms_bak').val(data.data.minid);
            		if(data.data.maxid==undefined){
            			$('#bdnum_bak').val('');
                    	$('#bdnum').val('');
            			return;
            		}
            		$('#bdnumdiv').show();
                	$('#bdnum_bak').val(parseInt(data.data.maxid)-parseInt(data.data.minid)+1);
                	$('#bdnum').val(parseInt(data.data.maxid)-parseInt(data.data.minid)+1);
            	}else if(3==type){
            		//校验一下产品和组合码规格，这两项是否一致
            		if($("#pbccount").val() != data.data.pbc_id ){
            			 bootbox.balert("产品规格和二维码规格不一致！");
        	             return;
            		}
//            		console.log(data);
            		$('#_pbcid').val("1*"+data.data.pbc_id);
            		//$('#_pbcidbak').val(data.data.pbc_id);
            		$('#_leftnub').val(data.data.count);
            		$('#xms').val(data.data.xminid);
            		$('#pms').val(data.data.minid);
            		$('#xme').val(data.data.xmaxid);
            		$('#pme').val(data.data.maxid);
            		$('#xme_bak').val(data.data.xmaxid);
            		$('#pme_bak').val(data.data.maxid);
            		$('#xms_bak').val(data.data.xminid);
            		$('#pms_bak').val(data.data.minid);
            		if(data.data.xmaxid==undefined){
            			$('#xmbdnum_bak').val('');
                    	$('#xmbdnum').val('');
            			return;
            		}
            		$('#xmbdnum_bak').val(parseInt(data.data.xmaxid)-parseInt(data.data.xminid)+1);
                	$('#xmbdnum').val(parseInt(data.data.xmaxid)-parseInt(data.data.xminid)+1);
            		if(data.data.maxid==undefined){
            			$('#bdnum_bak').val('');
                    	$('#bdnum').val('');
            			return;
            		}
            		$('#bdnumdiv').show();
                	$('#bdnum_bak').val(parseInt(data.data.maxid)-parseInt(data.data.minid)+1);
                	$('#bdnum').val(parseInt(data.data.maxid)-parseInt(data.data.minid)+1);
            	}
            },
            error:function(){
            }
       });
    });
    
    $("#xme").on("change",function(){
    	var xmebakn = $('#xme_bak').val();
    	var xmsbakn = $('#xms_bak').val();
    	var xmen = $('#xme').val();
    	if(parseInt(xmen)>parseInt(xmebakn)){
    		  bootbox.balert("箱码结束编号不能大于最大编号！");
    		  $('#xme').val(xmebakn);
              return;
    	}
    	if(parseInt(xmen)<parseInt(xmsbakn)){
  		  bootbox.balert("箱码结束编号不能小于开始编号！");
  		  $('#xme').val(xmebakn);
            return;
    	}
    	$('#xmbdnum_bak').val(parseInt($('#xme').val())-parseInt($('#xms').val())+1);
    	$('#xmbdnum').val(parseInt($('#xme').val())-parseInt($('#xms').val())+1);
    	$.get('/qrcodeprocut/resetendnobyxme', {id:$('#xme').val()}, function (data) {
    		 $('#pme').val(data);
    		 $('#bdnum_bak').val(parseInt($('#pme').val())-parseInt($('#pms').val())+1);
         	 $('#bdnum').val(parseInt($('#pme').val())-parseInt($('#pms').val())+1);
	    });
    	
    });
    
    $("#pme").on("change",function(){
    	var pmebakn = $('#pme_bak').val();
    	var pmsbakn = $('#pms_bak').val();
    	var pmen = $('#pme').val();
    	if(parseInt(pmen)>parseInt(pmebakn)){
    		  bootbox.balert("瓶码结束编号不能大于最大编号！");
    		  $('#pme').val(pmebakn);
              return;
    	}
    	if(parseInt(pmen)<parseInt(pmsbakn)){
	  		  bootbox.balert("瓶码结束编号不能小于开始编号！");
	  		  $('#pme').val(pmebakn);
	            return;
    	}
    	$('#bdnumdiv').show();
    	$('#bdnum_bak').val(parseInt(pmen)-parseInt(pmsbakn)+1);
    	$('#bdnum').val(parseInt(pmen)-parseInt(pmsbakn)+1);
    });
    
    // 追加绑定
    $('#md_new').on('show.bs.modal', function (event) {
        var _e = $(event.relatedTarget);
        var pname = _e.data("pname");
        var type = _e.data("type");
        var pcount = _e.data("pcount");
        //console.log(pname +"_______________"+ type +"-------------"+pcount);
	        if(pname && type && pcount){
	        	$("#search_pname").val(pname);
	        	$('#search_pname').attr("readonly",true);
	        	$("#pbccount").val(pcount);
	        	$("#type").val(type);
	        	$("#type").change();
	        	$("#type").after('<intpu type="hidden" name="type" value="'+type+'"/>');
	        	$('#type').attr("disabled","disabled");
	        }else{
	        	$("#search_pname").val("");
	        	$("#type").val("");
	        	$('#search_pname').attr("readonly",false);
	        	$('#type').removeAttr("disabled");
	        	
	        }
     
        });
    
    //更换产品名称
    $('#md_edit').on('show.bs.modal', function (event) {
        var _e = $(event.relatedTarget);
        var qcname = _e.data("qcname");
        var type = _e.data("type");
        var id = _e.data("id");
        if(id && qcname){
        	if(type == 3){
        		jQuery.ajax({
                    type:'get',
                    url:'/qrcodeproduct/qrcodepbc',
                    data:{'id':id},
                    dataType:'json',
                    cache:false,
                    success:function(data){
                    	$("#qrpcount").val(data.data.pcount);
                    	//console.log(data);
                    },
                    error:function(){
                    	tipper.danger("获取组合码规格失败，请重试");
                    }
               });
        		$("#id").val(id);
            	$("#_type").val(type);
            	$("#_qcname").val(qcname);
            	$('#_qcname').attr("readonly",true);
        	}else{
        		$("#id").val(id);
            	$("#_type").val(type);
            	$("#_qcname").val(qcname);
            	$('#_qcname').attr("readonly",true);
        	}
        	
        }
     
        });
    
    
    //接触绑定
    $("[name='btn_delete_bangdings']").click(function () {
        var id = $(this).data("qrcodeproductid");
        var type = $(this).data("type");
        bootbox.bconfirm("一旦解除绑定关系，该二维码号段将作废，无法继续使用？", function (re) {
            if (re) {
            	jQuery.ajax({
                    type:'post',
                    url:'/qrcodeproduct/delete',
                    data:{'id':id,'type':type},
                    dataType:'json',
                    cache:false,
                    success:function(data){
                    	
                    	tipper.success("操作成功！");
                    	window.location.href=window.location.href; 
                    	window.location.reload; 
                    },
                    error:function(){
                    	tipper.danger("解绑失败，请重试");
                    }
               });
             
            }
        });
    });
    
  //营销状态
    $("[name='btn_is_act']").click(function () {
        var id = $(this).data("id");
        var type = $(this).data("type");
        var qrtype = $(this).data("qrtype");
//        console.log(qrtype);
        if (qrtype == 2 ){
        	 bootbox.balert("普通码箱码不参与营销！");
             return;
        }
        bootbox.bconfirm("确定更改营销状态？", function (re) {
            if (re) {
            	jQuery.ajax({
                    type:'post',
                    url:'/qrcodeproduct/upact',
                    data:{'id':id,'type':type},
                    dataType:'json',
                    cache:false,
                    success:function(data){
                    	
                    	tipper.success("操作成功！");
                    	window.location.href=window.location.href; 
                    	window.location.reload; 
                    },
                    error:function(){
                    	tipper.danger("解绑失败，请重试");
                    }
               });
             
            }
        });
    });
    
    
    //更改绑定产品
    $("[name='btn_edit_save']").click(function () {
    	  var form = window.form_edit;
          var id = form.id.value;
          var pname = form.pname.value;
          var batch_nub = form.batch_nub.value;
          var type = form.type.value;
          var pid = form.pid.value;
          var qrpcount = form.qrpcount.value;
          var pbccount1 = form.pbccount1.value;
          //console.log(qrpcount +"---------"+pbccount1);
          if( type ==3 &&qrpcount != pbccount1 ){
        	  bootbox.balert("更换产品的规格与组合二维码的规格不一致！");
              return;
          }
          if (!pname) {
              bootbox.balert("二维码名称输入有误！");
              return;
          }else{
          	var index = pname.lastIndexOf("_"); 
          	if(-1==index){
          		 bootbox.balert("产品名称选择有误！");
                   return;
          	}
          	
          }
        bootbox.bconfirm("请确认是否更改绑定产品？", function (re) {
            if (re) {
            	jQuery.ajax({
                    type:'post',
                    url:'/qrcodeproduct/edit',
                    data:{'id':id,'type':type,'pname':pname,'batch_nub':batch_nub,'pid':pid},
                    dataType:'json',
                    cache:false,
                    success:function(data){
                    	tipper.success("操作成功！");
                    	window.location.href=window.location.href; 
                    	window.location.reload; 
                    },
                    error:function (data, status) {
                        // tipper.danger(data.responseJSON.msg);
                        bootbox.alert({
                            message: data.responseJSON.msg,
                            size: "small",
                            title: "<i class='fa fa-info-circle text-yellow'></i> 提示"
                        });
                    }
               });
             
            }
        });
    });
    
    
  //数据导出
    $("[name='btn_qrcodeproduct_export']").click(function () {
        var pname = $("[name='pname']").val();
        var qcname = $("[name='qcname']").val();
        var sta = $("[name='sta']").val();
        
        //有数据时才能导出
        if($("#resultTotal_hidden").val() != 0){
        	bootbox.bconfirm("确定是否导出？", function (re) {
                if (re) {
                	 var url="/qrcodeproduct/export?qcname="+qcname+"&sta="+sta+"&pname="+pname;
                     window.open(url);
                }
            });
        }else{
        	bootbox.balert("没有数据，无法导出!");
        }
    });
    
  
});
